<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
use think\facade\Route;
use app\index\model\Catalog;

Route::pattern([
	'routeName'  => '[\w\-]+',
	'parameter'  => '[\w\-]+',
	'lang'       => '[\w\-]+',
]);
$pathInfo      = str_replace('.' . request()->ext(), '', request()->pathinfo());
$pathArr       = explode('/', $pathInfo);
$langAllow     = array_column(config('lang.lang_allow'), 'name');
$langList      = array_column(unserialize(config('app.language')), 'name');
$langExis      = in_array($pathArr[0], $langList);
$pluginPage    = plugin_route('page');
$pluginSingle  = plugin_route('single');
$pluginCatalog = plugin_route('catalog');
$authority     = true;   
$routeInfo     = [];
$middleware    = [
	\think\middleware\LoadLangPack::class,
	app\index\middleware\AppCheck::class,
	app\index\middleware\CatalogCheck::class,
	app\index\middleware\ConfigCheck::class,
	app\index\middleware\CommonCheck::class,
];
if ($langExis) {
	$routeName = in_array($pathArr[0], $langAllow) ? count($pathArr) > 1 ? $pathArr[1] : "" : "404";
} else {
	$routeName = $pathArr[0];
}
$routeName    = empty($routeName) ? 'index' : $routeName;
$_GET['lang'] = $langExis ? $pathArr[0] : config('lang.default_lang');
$catalogArr   = Catalog::withoutField('status,create_time,language,group_id')
->where('status', 1)
->where('language', $_GET['lang'])
->order('sort','desc')
->append(['url'])
->cache('catalog_' . $_GET['lang'])
->select()
->toArray();
$field   = is_numeric($routeName) ? 'id' : 'seo_url';
$catalog = [];
foreach ($catalogArr as $key => $value) {
	if ($value[$field] == $routeName) {
		$catalog = $value;
	}
}
// 详情页分类
$singleRouteLength = $langExis ? 3 : 2;
if (empty($catalog) && count($pathArr) === $singleRouteLength) {
	foreach ($catalogArr as $key => $value) {
		if ($value['type'] == $routeName && $value['pid'] === 0) {
			$catalog = $value;
		}
	}
}
$routeInfo['catalogArr'] = $catalogArr;
$routeInfo['catalog'] = $catalog;
// 路由注册
switch ($routeName) {
	case 'search':
		// 搜索
		Route::rule('search/:keyword', 'page/search')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/search/:keyword', 'page/search')->append($routeInfo)->middleware($middleware);
		break;
	case 'verify':
		// 验证码
		Route::rule('verify', 'page/verify');
		Route::rule(':lang/verify', 'page/verify');
		break;
	case 'user':
		// 登录注册之类
		Route::rule(':lang/user/login', 'user/login')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/logout', 'user/logout')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/password', 'user/password')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/register', 'user/register')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/sendRegisterEmailCode', 'user/sendRegisterEmailCode')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/sendPasswordEmailCode', 'user/sendPasswordEmailCode')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/isNeedVerification', 'user/isNeedVerification')->append($routeInfo)->middleware($middleware);
		Route::rule('user/login', 'user/login')->append($routeInfo)->middleware($middleware);
		Route::rule('user/logout', 'user/logout')->append($routeInfo)->middleware($middleware);
		Route::rule('user/password', 'user/password')->append($routeInfo)->middleware($middleware);
		Route::rule('user/register', 'user/register')->append($routeInfo)->middleware($middleware);
		Route::rule('user/sendRegisterEmailCode', 'user/sendRegisterEmailCode')->append($routeInfo)->middleware($middleware);
		Route::rule('user/sendPasswordEmailCode', 'user/sendPasswordEmailCode')->append($routeInfo)->middleware($middleware);
		Route::rule('user/isNeedVerification', 'user/isNeedVerification')->append($routeInfo)->middleware($middleware);
		// 个人中心（需要登录）
		Route::rule(':lang/user/upload', 'personal/upload')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/index', 'personal/index')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/balance', 'personal/balance')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/set', 'user/set')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/integral', 'personal/integral')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/integralSignin', 'personal/integralSignin')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/integralLog', 'personal/integralLog')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/balanceLog', 'personal/balanceLog')->append($routeInfo)->middleware($middleware);
		Route::rule(':lang/user/invite', 'personal/invite')->append($routeInfo)->middleware($middleware);
		Route::rule('user/upload', 'personal/upload')->append($routeInfo)->middleware($middleware);
		Route::rule('user/index', 'personal/index')->append($routeInfo)->middleware($middleware);
		Route::rule('user/balance', 'personal/balance')->append($routeInfo)->middleware($middleware);
		Route::rule('user/set', 'personal/set')->append($routeInfo)->middleware($middleware);
		Route::rule('user/integral', 'personal/integral')->append($routeInfo)->middleware($middleware);
		Route::rule('user/integralSignin', 'personal/integralSignin')->append($routeInfo)->middleware($middleware);
		Route::rule('user/integralLog', 'personal/integralLog')->append($routeInfo)->middleware($middleware);
		Route::rule('user/balanceLog', 'personal/balanceLog')->append($routeInfo)->middleware($middleware);
		Route::rule('user/invite', 'personal/invite')->append($routeInfo)->middleware($middleware);
		break;
	case '404':
		// 404页面
		Route::rule($routeName, 'page/miss404')->append($routeInfo)->middleware($middleware);
		break;
	default:
		// 插件自定义路由
		foreach ($pluginPage as $key => $val) {
			if ($val['name'] === $routeName) {
				$routeInfo = array_merge($routeInfo, $val);
				$routeInfo['bind'] = 'plugin';
			}
		}
		// 系统分类路由
		if (empty($routeInfo['bind'])) {
			$catalogRouteLength = $langExis ? 2 : 1; // 未分页
			$catalogPageRouteLength = $langExis ? 4 : 3; //已经分页
			$bool = count($pathArr) === $catalogRouteLength;
			$pageBool = count($pathArr) === $catalogPageRouteLength && strstr($pathInfo, '/page/');
			if ($bool || $pageBool || $routeName === 'index') {
				if ($catalog) {
					if (!empty($catalog['group_id'])){
						$userInfo = session('index_user');
						if (empty($userInfo) || ! in_array($userInfo['group_id'], $catalog['group_id'])) {
							$authority = false;
						}
					}
					if ($catalog['type'] === 'page') {
						$routeInfo['bind']      = 'system';
						$routeInfo['routeName'] = $routeName;
					} else {
						foreach ($pluginCatalog as $key => $val) {
							if ($val['search']['type'] === $catalog['type']) {
								$routeInfo = array_merge($routeInfo, $val);
								$routeInfo['bind'] = 'plugin';
							}
						}
					}
				}
			}
		}
		// 插件详情路由
		if (empty($routeInfo['bind'])) {
			foreach ($pluginSingle as $key => $val) {
				if ($val['name'] === $routeName  &&  count($pathArr) === $singleRouteLength) {
					$routeInfo = array_merge($routeInfo, $val);
					$routeInfo['bind'] = 'plugin';
				}
			}
		}
		// 插件常规路由
		if (empty($routeInfo['bind'])) {
			$pluginRouteLength = $langExis ? 4 : 3;
			if (count($pathArr) === $pluginRouteLength) {
				$pluginName = $langExis ? $pathArr[1] : $pathArr[0];
				$pluginController = $langExis ? $pathArr[2] : $pathArr[1];
				$pluginAction = $langExis ? $pathArr[3] : $pathArr[2];
				$routeInfo = [
					"name"    => $pluginController . '/' . $pluginAction,
					"route"   => $pluginController . '/' . $pluginAction,
					"plugin"  => $pluginName,
					"title"   => "插件路由",
					"bind"    => "plugin",
					"type"    => "page",
					"catalog" => [],
					"catalogArr" => $catalogArr,
				];
				// 插件个人中心模块绑定登录检测中间件
				if ($pluginController === 'user') array_push($middleware, app\index\middleware\LoginCheck::class);
			}
		}
		// 开始注册
		if (!empty($routeInfo['bind'])) {
			if ($authority) {
				if ($routeInfo['bind'] === 'plugin') {
					$bind = 'plugins/index';
					switch ($routeInfo['type']) {
						case 'single':
							$route = $langExis ? ':lang/:routeName/:parameter' : ':routeName/:parameter';
							break;
						case 'catalog':
							// 分页
							$route = $langExis ? ':lang/:routeName/page/:page' : ':routeName/page/:page';
							$route = $langExis ? ':lang/:routeName' : ':routeName';
							break;	
						case 'page':
							$route = $langExis ? ':lang/:routeName' : ':routeName';
							break;
					}
				} else if ($routeInfo['bind'] === 'system') {
					$bind  = 'page/index';
					$route = $langExis ? ':lang/:routeName' : ':routeName';
					if ($routeName === 'index') {
						$route = $langExis ? ':lang' : '/';
					}
				}
				Route::rule($route, $bind)->append($routeInfo)->middleware($middleware);
			} else {
				Route::rule($routeName, 'page/miss403')->append($routeInfo)->middleware($middleware);
			}
		} else {
			Route::rule($routeName, 'page/miss404')->append($routeInfo)->middleware($middleware);
		}
		break;
}